package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.core.entity.BaseDO;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IEmpFamilyDAO;
import org.jsola.hr.dto.EmpFamilyAddDTO;
import org.jsola.hr.dto.EmpFamilyDTO;
import org.jsola.hr.dto.EmpFamilyUpdateDTO;
import org.jsola.hr.entity.EmpFamilyDO;
import org.jsola.hr.query.EmpFamilyQuery;
import org.jsola.hr.service.IEmpFamilyService;
import org.jsola.hr.vo.EmpFamilyListVO;
import org.jsola.hr.vo.EmpFamilyVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工家庭成员
 *
 * @author zhr
 */
@Service("hrEmpFamilyServiceImpl")
public class EmpFamilyServiceImpl implements IEmpFamilyService {

    @Autowired
    private IEmpFamilyDAO empFamilyDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public EmpFamilyVO save(EmpFamilyAddDTO empFamilyAddDTO, TokenUser tokenUser) {
        // 转DO
        EmpFamilyDO empFamilyDO = empFamilyAddDTO.to(EmpFamilyDO.class);

        // 校验员工和公司
        checkEmpAndCompany(empFamilyAddDTO.getEmpId(), empFamilyAddDTO.getCompanyId(), tokenUser.getSiteId());
        // 保存
        empFamilyDO = save(empFamilyDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return empFamilyDO.to(EmpFamilyVO.class);
    }

    /**
     * 校验员工和公司
     *
     * @param empId     员工id
     * @param companyId 公司id
     * @param siteId    站点
     */
    private void checkEmpAndCompany(String empId, String companyId, String siteId) {
        ParamException.hasLength(empId, "员工id不能为空");
        ParamException.hasLength(companyId, "公司id不能为空");
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(EmpFamilyUpdateDTO empFamilyUpdateDTO, TokenUser tokenUser) {
        //转DO
        EmpFamilyDO empFamilyDO = empFamilyUpdateDTO.to(EmpFamilyDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(empFamilyDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... empFamilyIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) empFamilyIds);
    }


    @Override
    public EmpFamilyVO selectById(String empFamilyId, String siteId) {
        EmpFamilyDO empFamilyDO = selectDOById(empFamilyId, siteId);
        if (empFamilyDO == null) {
            return null;
        }
        return empFamilyDO.to(EmpFamilyVO.class);
    }

    @Override
    public List<EmpFamilyListVO> select(EmpFamilyQuery empFamilyQuery, String siteId) {
        List<EmpFamilyDO> empFamilyDOList = selectDO(empFamilyQuery, siteId);
        if(CollectionUtils.isEmpty(empFamilyDOList)) {
            return empFamilyDOList == null ? null : new ArrayList<>();
        }
        return empFamilyDOList.stream()
                .map(empFamilyDO -> empFamilyDO.to(EmpFamilyListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(EmpFamilyQuery empFamilyQuery, String siteId) {
        Example example = buildExample(empFamilyQuery,siteId);
        return empFamilyDAO.selectCountByExample(example);
    }

    @Override
    public Page<EmpFamilyListVO> selectPage(EmpFamilyQuery empFamilyQuery, String siteId) {
        Example example = buildExample(empFamilyQuery,siteId);
        Page<EmpFamilyDO> page = empFamilyDAO.selectPageByExample(example,
                empFamilyQuery.getPageNo(),
                empFamilyQuery.getPageSize());

        return page.to(EmpFamilyListVO.class);
    }

    @Override
    public EmpFamilyDO selectDOById(String empFamilyId, String siteId) {
        return listById(empFamilyId, siteId);
    }

    @Override
    public List<EmpFamilyDO> selectDO(EmpFamilyQuery empFamilyQuery, String siteId) {
        Example example = buildExample(empFamilyQuery,siteId);
        return empFamilyDAO.selectByExample(example);
    }

    @Override
    public List<EmpFamilyDO> listByEmpId(String empId, String siteId) {
        Example example = new Example(EmpFamilyDO.class);
        example.and()
                .andEqualTo("empId", empId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        example.orderBy("gmtCreate");
        return empFamilyDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void deleteByCompanyId(String companyId, TokenUser tokenUser) {
        Example example = new Example(EmpFamilyDO.class);
        example.and()
                .andEqualTo("companyId", companyId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        // 逻辑删除
        List<EmpFamilyDO> list = empFamilyDAO.selectByExample(example);
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void publishEmpFamilyList(List<EmpFamilyDTO> empFamilyList, String companyId, String empId, TokenUser tokenUser) {
        // 删除某个员工所有的
        deleteByEmpId(empId, tokenUser);

        if (CollectionUtils.isEmpty(empFamilyList)) {
            return;
        }

        empFamilyList.forEach(
                empFamilyDTO -> {
                    empFamilyDTO.setCompanyId(companyId);
                    empFamilyDTO.setEmpId(empId);
                    // 新增
                    EmpFamilyAddDTO empFamilyAddDTO = empFamilyDTO.to(EmpFamilyAddDTO.class);
                    save(empFamilyAddDTO, tokenUser);
                }
        );
    }    
    
    /**
     * 删除某个员工所有的
     *
     * @param empId     员工id
     * @param tokenUser 当前用户
     */
    private void deleteByEmpId(String empId, TokenUser tokenUser) {
        // 逻辑删除
        List<EmpFamilyDO> list = listByEmpId(empId, tokenUser.getSiteId());
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }

    /**
     * 根据查询参数，构建example

     * @param empFamilyQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(EmpFamilyQuery empFamilyQuery, String siteId) {
        Example example = new Example(EmpFamilyDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (empFamilyQuery.getEmpId() != null) {
            example.and().andEqualTo("empId", empFamilyQuery.getEmpId());
        }
        if (empFamilyQuery.getName() != null) {
            example.and().andEqualTo("name", empFamilyQuery.getName());
        }
        if (empFamilyQuery.getRelation() != null) {
            example.and().andEqualTo("relation", empFamilyQuery.getRelation());
        }
        if (empFamilyQuery.getPhone() != null) {
            example.and().andEqualTo("phone", empFamilyQuery.getPhone());
        }
        if (empFamilyQuery.getWorkUnit() != null) {
            example.and().andEqualTo("workUnit", empFamilyQuery.getWorkUnit());
        }
        if (empFamilyQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", empFamilyQuery.getCompanyId());
        }
        // 排序
        ExampleKit.setExampleOrder(example,empFamilyQuery.getOrders());
        return example;
    }
}




